﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.Support;
using MS.InformationManagement.Support.Constants;
using System.Data;
using MS.InformationManagement.DAL.DTOs;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Globalization;
using MS.InformationManagement.DAL.DocumentCenter;

namespace MS.InformationManagement.BLL.ShippingControlTemplates
{
    public class ShippingControlTemplates
    {

        public static List<PlanillasDTO> SearchRadicados()
        {
            List<string> viewFields = new List<string>(){ 
                CustomSiteColumns.FIELD_DOCUMENT_RADICADO, 
                CustomSiteColumns.FIELD_DOCUMENT_NIT,
                CustomSiteColumns.FIELD_DOCUMENT_RAZON,
                CustomSiteColumns.FIELD_DOCUMENT_SIGLA,
                CustomSiteColumns.FIELD_DOCCUMENT_REPRESENTANTE,
                CustomSiteColumns.FIELD_DOCUMENT_CEDULA,
                CustomSiteColumns.FIELD_DOCUMENT_NOMBRES,
                CustomSiteColumns.FIELD_DOCUMENT_APELLIDO1,
                CustomSiteColumns.FIELD_DOCUMENT_APELLIDO2,
                CustomSiteColumns.FIELD_DOCUMENT_FOLIOS,
                CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX,
                CustomSiteColumns.FIELD_ARCHIVE_ASSIGNED,
                CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED,
                CustomSiteColumns.FIELD_DOCUMENT_EMAIL,
                "ID"

            };

            string queryByRadicadoId = string.Format(@"<Where><And><Eq><FieldRef Name='{0}' /><Value Type='Boolean'>1</Value></Eq><Neq><FieldRef Name='{1}' /><Value Type='Boolean'>1</Value></Neq></And></Where>", CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT, CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED);
            List<string> listFields = new List<string>() { "Title" };
            DataTable results = QuerySiteHelper.GetDataFromSiteWithElevatedPrivileges(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, listFields, queryByRadicadoId);

            return convertTableToEntities(results);
        }

        public static List<PlanillasDTO> SearchRadicados(string IdRadicado)
        {
            List<string> viewFields = new List<string>(){ 
                CustomSiteColumns.FIELD_DOCUMENT_RADICADO, 
                CustomSiteColumns.FIELD_DOCUMENT_NIT,
                CustomSiteColumns.FIELD_DOCUMENT_RAZON,
                CustomSiteColumns.FIELD_DOCUMENT_SIGLA,
                CustomSiteColumns.FIELD_DOCCUMENT_REPRESENTANTE,
                CustomSiteColumns.FIELD_DOCUMENT_CEDULA,
                CustomSiteColumns.FIELD_DOCUMENT_NOMBRES,
                CustomSiteColumns.FIELD_DOCUMENT_APELLIDO1,
                CustomSiteColumns.FIELD_DOCUMENT_APELLIDO2,
                CustomSiteColumns.FIELD_DOCUMENT_FOLIOS,
                CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX,
                CustomSiteColumns.FIELD_ARCHIVE_ASSIGNED,
                CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED,
                CustomSiteColumns.FIELD_DOCUMENT_EMAIL,
                "ID"

            };

            string queryByRadicadoId = string.Format(@"<Where><And><And><Contains><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Contains><Eq><FieldRef Name='{2}' /><Value Type='Boolean'>1</Value></Eq></And><And><Contains><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Contains><Neq><FieldRef Name='{3}' /><Value Type='Boolean'>1</Value></Neq></And></And></Where>", CustomSiteColumns.FIELD_DOCSET_ID_RADICADO, IdRadicado,  CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT, CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED);
            List<string> listFields = new List<string>() { "Title" };
            DataTable results = QuerySiteHelper.GetDataFromSiteWithElevatedPrivileges(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, listFields, queryByRadicadoId);

            return convertTableToEntities(results);
        }

        private static List<PlanillasDTO> convertTableToEntities(DataTable inputData)
        {
            //CustomSiteColumns.DELIVERY_DATE]
            List<PlanillasDTO> ListPlanillas = new List<PlanillasDTO>();

            foreach (DataRow row in inputData.Rows)
            {
                GetInfoEnvio(ListPlanillas, row);
            }

            return ListPlanillas;
        }

        private static void GetInfoEnvio(List<PlanillasDTO> ListPlanillas, DataRow row)
        {
            try
            {
                using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
                {
                    var Envios = (from item in dc.EnviosDeCorreo
                                  where item.NoRadicado == row[CustomSiteColumns.FIELD_DOCUMENT_RADICADO].ToString()
                                  && item.Enviado == true
                                  select item);
                    foreach (EnvíoDeCorrespondencia entity in Envios)
                    {
                        int _folios = (int)double.Parse(row[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS] == null ? "0" : row[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS].ToString(), CultureInfo.InvariantCulture);
                        int _anexos = (int)double.Parse(row[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX] == null ? "0" : row[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX].ToString(), CultureInfo.InvariantCulture);
                        int _idItem = (int)double.Parse(entity.IdDocumento == null ? "0" : entity.IdDocumento.Value.ToString(), CultureInfo.InvariantCulture);
                        ListPlanillas.Add(new PlanillasDTO()
                        {
                      
                            IdList = new Guid(row[0].ToString()),
                            IdInternoRadicado = int.Parse(row["ID"].ToString()),
                            IdItem = _idItem,
                            NoRadicado = row[CustomSiteColumns.FIELD_DOCUMENT_RADICADO]+ "",
                            IdItemMedioEnvio = entity.Id.Value,
                            Folios = _folios,
                            Anexos = _anexos,
                            UsuarioAsignado = row[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] +"",
                            Direccion = entity.Dirección,
                            Telefono = entity.Teléfono,
                            Destinatario = entity.RemitenteDestinatario,
                            FechaEnvio = entity.FechaDeEnvío.Value,
                            EsCopia = entity.Copia.Value,
                            Ciudad = entity.City.Label,
                            NombreBilioteca = SPContext.Current.Web.Lists[new Guid(row[0].ToString())].Title,
                            Email = row[CustomSiteColumns.FIELD_DOCUMENT_EMAIL] + "",
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static IEnumerable<MotivosDeDevolucion> GetMotivosEnvio()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                return dc.MotivosDeDevolución.ToList();
            }
        }
    }
}

